package jf.jextn.xml;

import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import jf.jextn.io.IOUtil;

public class XmlUtil {

    public static String formatXml(String xml) throws IOException {
        Reader reader = IOUtil.asReader(xml);
        Writer writer = new StringWriter(xml.length() + 20);

        formatXml(new StreamSource(reader), new StreamResult(writer));

        IOUtil.closeQuietly(reader);
        IOUtil.closeQuietly(writer);

        return writer.toString();
    }

    public static void formatXml(Source xmlSource, Result xmlResult) throws IOException {
        try {
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            if (!Boolean.getBoolean("jextn.xml.indent-amount.disable")) {
                transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            }

            transformer.setOutputProperty(OutputKeys.METHOD, "xml");

            transformer.transform(xmlSource, xmlResult);

        } catch (TransformerException e) {
            throw new IOException(e);
        }
    }

}
